package org.rguess.patterns.responsibility.singleton;

import java.util.*;

@SuppressWarnings({"unchecked","rawtypes"})
class LoadBalancer {
	private static LoadBalancer Balancer;
	private ArrayList ArrayList_Server = new ArrayList();
	private Random random = new Random();

	protected LoadBalancer()
	// 构造函数
	{
		ArrayList_Server.add("服务器 I");
		ArrayList_Server.add("服务器 II");
		ArrayList_Server.add("服务器 III");
		ArrayList_Server.add("服务器 IV");
		ArrayList_Server.add("服务器 V");
	}

	// 创建实例的唯一入口
	public static synchronized LoadBalancer GetLoadBalancer() {
		if (Balancer == null)
			Balancer = new LoadBalancer();
		return Balancer;
	}

	public String Server() {
		Object array[] = ArrayList_Server.toArray();
		return array[random.nextInt(array.length)].toString();
	}
}

public class SingletonApp {
	public static void main(String[] args) {
		LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
		// 创建类的实例
		LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
		LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
		LoadBalancer b4 = LoadBalancer.GetLoadBalancer();
		if ((b1 == b2) && (b2 == b3) && (b3 == b4))
			// 判断实例是否相同
			System.out.println("同步运行相同的实例对象");
		System.out.println(b1.Server());
		System.out.println(b2.Server());
		System.out.println(b3.Server());
		System.out.println(b4.Server());
	}
}
